package com.example.recite_words.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.example.recite_words.Bean.Questions;
import com.example.recite_words.MainActivity;
import com.example.recite_words.R;
import com.example.recite_words.util.MyDatabaseHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Wrongbook extends MainActivity {
    SharedPreferences sharedpreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wrong);
        List<HashMap<String, Object>> wrongData = new ArrayList<HashMap<String, Object>>();
        //initial data
        MyDatabaseHelper db1=new MyDatabaseHelper(this);
        try {
            db1.createDB();
        } catch (IOException ioe) {
            throw new Error("Database not created....");
        }

        try {
            db1.openDB();
        } catch (SQLException sqle) {
            throw sqle;
        }
        SQLiteDatabase db;
        db= openOrCreateDatabase("words", Context.MODE_PRIVATE, null);
        Cursor cursor=db.query("Sheet1",null,null,
                null, null,null,null);

        sharedpreferences = getSharedPreferences("wrongData", Context.MODE_PRIVATE);
        final int[] wrongNum = {sharedpreferences.getInt("wrongNum", 0)};
        ArrayList<Integer> wrongIndex=new ArrayList<>();
        for(int i=1;i<=wrongNum[0];++i){
            int index=sharedpreferences.getInt("wrong"+i,1);
            if(!wrongIndex.contains(index))
                wrongIndex.add(index);
        }
        wrongData.clear();
        for(int i=0;i<wrongIndex.size();++i){
            cursor.moveToPosition(wrongIndex.get(i));
            Questions question=new Questions();
            String w="", t="";
            int temp=cursor.getColumnIndex("words");
            if(temp>=0)  w=cursor.getString(temp);
            temp=cursor.getColumnIndex("translation");
            if(temp>=0)  {
                String[] meaning = cursor.getString(temp).split("\n");
                t=meaning[0];
            }
            HashMap<String, Object>item = new HashMap<String, Object>();
            item.put("word",w);
            item.put("translation",t);
            wrongData.add(item);
        }
        cursor.close();
        ListView listView = (ListView)this.findViewById(R.id.wrongList);
        SimpleAdapter adapter = new SimpleAdapter(this, wrongData, R.layout.item,
                new String[]{"word", "translation"},
                new int[]{R.id.word, R.id.translation});
        //实现列表的显示
        listView.setAdapter(adapter);
    }
}